﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace MvcContrib.Shp.UI.Menu
{
    /// <summary>
    /// Menu Item used to contain user-defined Content.
    /// </summary>
    public class TemplateMenuItem : MenuItem
    {
        public TemplateMenuItem(ViewContext viewContext, MenuSettings settings)
            : base(viewContext, settings)
        {
        }

        public Func<object, object> ItemTemplate { get; set; }

        protected override bool IncludeItem()
        {
            return ItemTemplate != null && base.IncludeItem();
        }

        public override string RenderItem()
        {
            if (ItemTemplate == null) return string.Empty;

            PrepareAttributes();

            // only item attributes are relevant, so anchor and list attributes are ignored
            var itemAttributes = BuildHtmlAttributes(GetItemAttributes());
            if (itemAttributes.Length > 0) itemAttributes = " " + itemAttributes;

            var builder = new StringBuilder();

            builder.AppendFormat("<li{0}>", itemAttributes);

            var html = ItemTemplate(new object()).ToString();
            builder.Append(html);

            // temlate menu item cannot have child menu items, so they are ignored

            builder.Append("</li>");

            return builder.ToString();
        }
    }
}
